package com.hsxc.cdz.controller.appController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hsxc.cdz.base.bean.MyUser;
import com.hsxc.cdz.mgmt.user.MyUserManager;

import net.sf.json.JSONObject;

/**
 * app用户登录和退出请求
 *
 * @author wpfei
 */
@Controller
@RequestMapping("/account")
public class appLoginController {
    //========================================================================================================
    protected static Logger logger = Logger.getLogger("applogincontroller");

    private final static int USERTYPE = 2;
    @Autowired
    MyUserManager myUserManager;
    //=======================================================================================================
    //处理请求

    /**
     * 接收登录请求
     *
     * @param
     * @param
     * @return json数据
     * @throws JSONException
     */
    @SuppressWarnings("finally")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object applogin(@RequestBody String jsonObj, HttpServletRequest request, HttpSession httpSession) throws JSONException {
        MyUser myUser = null;
        Session appSession = null;
        UsernamePasswordToken token = null;
        JSONObject resultJSONObject = new JSONObject();
        String errorMessage = "";
        boolean isAuth = false;
        logger.debug("===========================" + "httpSession session id: " + httpSession.getId().toString() + "=====================");
        org.json.JSONObject jsonObject2 = new org.json.JSONObject(jsonObj);
        String tel = jsonObject2.getString("tel");
        String password = jsonObject2.getString("password");
        logger.debug("========================" + tel + "====" + password + "==========================================");
        if (tel != null && password != null) {
            token = new UsernamePasswordToken(tel, password);
        }

        try {
            //设置用户类型为1 表示后台用户，方便认证和授权
            myUserManager.setUSERTYPE(USERTYPE);
            Subject appUser = SecurityUtils.getSubject();
            appSession = appUser.getSession();
            logger.debug("======================" + appSession + "====================" + "user的具体内容" + appUser);
            appUser.login(token);
            String userID = (String) appUser.getPrincipal();
            logger.debug("=======================" + "username: " + userID + "==============================");
            logger.debug("==========================" + "session id: " + appSession.getId().toString() + "========================");
            logger.info("=========================" + "User [" + userID + "] logged in successfully." + "======================");
            logger.info("=========================" + "User is authenticated:  " + appUser.isAuthenticated() + "==========================");
            appSession.setAttribute("APPUSERNAME", userID);
            isAuth = appUser.isAuthenticated();
            httpSession.setAttribute("appuser", appUser);
        } catch (UnknownAccountException uae) {
            errorMessage = "用户认证失败：" + "username wasn't in the system.";
            logger.info(errorMessage);
        } catch (IncorrectCredentialsException ice) {
            errorMessage = "用户认证失败：" + "password didn't match.";
            logger.info(errorMessage);
        } catch (LockedAccountException lae) {
            errorMessage = "用户认证失败：" + "account for that username is locked - can't login.";
            logger.info(errorMessage);
        } catch (AuthenticationException e) {
            errorMessage = "登录失败错误信息：" + e;
            logger.error(errorMessage);
            e.printStackTrace();
            token.clear();
        } finally {
            if (isAuth) {
                logger.info("=========================" + "请求头" + request + "===========================");
                token.setRememberMe(true);
                myUser = myUserManager.loadMyUserByMobile(tel);
                resultJSONObject.put("success", true);
                resultJSONObject.put("sid", appSession.getId().toString());
                resultJSONObject.put("logIn", true);
                resultJSONObject.put("userInfo", myUser);
                errorMessage = "用户登录：" + "该用户登陆成功";
                logger.info(errorMessage);
            } else {
                httpSession.setAttribute("ErrorMessage", errorMessage);
                resultJSONObject.put("success", false);
                resultJSONObject.put("logIn", false);
                resultJSONObject.put("userInfo", null);
                errorMessage = "用户认证失败：" + "账户未认证成功";
                logger.info(errorMessage);
            }
            return resultJSONObject;
        }

    }

//================================================================================================================	

    /**
     * 退出请求
     *
     * @return json字符串
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public Object applogout() {
        logger.debug("Received request to log out");
        Subject appUser = SecurityUtils.getSubject();
        logger.debug("==========================" + appUser + "==================================================");
        appUser.logout();
        logger.info("=================================" + "该用户注销成功" + "========================================");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", true);
        JSONObject jsonObject3 = new JSONObject();
        jsonObject3.put("logIn", false);
        jsonObject3.put("userInfo", null);
        jsonObject.put("data", jsonObject3);
        return jsonObject;
    }
}
